/**
 *@Time    : 2021/11/12 22:28
 *@Author  : Shuai Jhou
 *@File    : OrderService
 *@Software: GoLand
 */

package services

import (
	"context"
	"errors"
	"fmt"
	"google.golang.org/grpc/metadata"
	"log"
)

type OrderService struct {
	auth *AuthServer
}

type AuthServer struct{}

func (a *AuthServer) GetAppKey() string {
	return "go-programming-tour-book"
}

func (a *AuthServer) GetAppSecret() string {
	return "Jhou-Shuai"
}

func (a *AuthServer) Check(ctx context.Context) error {
	md, _ := metadata.FromIncomingContext(ctx)

	var appKey, appSecret string
	if value, ok := md["app_key"]; ok {
		appKey = value[0]
	}
	if value, ok := md["app_secret"]; ok {
		appSecret = value[0]
	}
	if appKey != a.GetAppKey() || appSecret != a.GetAppSecret() {
		return errors.New("unauthorized Failed")
	}

	return nil
}

func (s *OrderService) NewOrder(ctx context.Context, orderRequest *OrderRequest) (*OrderResponse, error) {
	fmt.Println(orderRequest.OrderMain)
	md, _ := metadata.FromIncomingContext(ctx)
	log.Printf("md: %+v \n", md)
	if err := s.auth.Check(ctx); err != nil {
		return &OrderResponse{
			Status:  "Error",
			Message: err.Error(),
		}, nil
	}

	err := orderRequest.OrderMain.Validate()
	if err != nil {
		return &OrderResponse{
			Status:  "Error",
			Message: err.Error(),
		}, nil
	}

	// 超时
	//time.Sleep(10 * time.Second)

	return &OrderResponse{
		Status:  "Ok",
		Message: "Successfully",
	}, nil
}
